// pages/bidding/bidding.js
import { Bidding } from '../../models/bidding'

const biddingModel = new Bidding()

Page({
  data: {
    showLoading: false,
    showSkeleton: true,
    show: false,
    data: [],
    page: 1,
    searchValue: '',
    showDialog: false,
    sharePath: '/pages/bidding/bidding',
    shareTitle: '招供货商合作',
    shareImg: ''
  },
  onLoad(options) {
    this.init()
  },
  onPullDownRefresh() {
    this.setData({
      page: 1
    })
    this.search()
  },

  onReachBottom() {
    this.setData({
      page: this.data.page + 1
    })
    this.search('more')
  },

  toNewPage(event) {
    let path = event.currentTarget.dataset.path
    let id =
      (event.currentTarget.dataset.item &&
        event.currentTarget.dataset.item.id) ||
      0
    wx.navigateTo({
      url: `/pages/${path}/${path}?id=${id}`
    })
  },

  search(type) {
    // 查找数据
    this.getBiddingList(type)
  },

  finish() {
    this.search()
    this.setData({
      show: false
    })
  },

  getBiddingList(type) {
    // 获取供应商列表
    biddingModel.biddingList(
      {
        page: this.data.page,
        title: this.data.searchValue
      },
      (res) => {
        this.setData({
          data: type == 'more' ? [...this.data.data, ...res.rows] : res.rows,
          showLoading: res.rows.length >= 10,
          showDialog: !wx.getStorageSync('showCategoryDialog')
        })
        setTimeout(() => {
          this.setData({
            showSkeleton: false
          })
        }, 500)
        wx.stopPullDownRefresh()
      }
    )
  },

  toNewTab(event) {
    let path = event.currentTarget.dataset.path
    wx.switchTab({
      url: `/pages/${path}/${path}`
    })
  },

  init() {
    this.getBiddingList()
  },

  onChange(e) {
    this.setData({
      searchValue: e.detail
    })
  },
  onShowDialog() {
    this.setData({
      showDialog: true
    })
  },

  closeDialog() {
    this.setData({
      showDialog: false
    })
    wx.setStorageSync('showCategoryDialog', true)
  },

  sleep() {
    // 延时 解决部分安卓手机setData过慢，分享图链接不改变问题
    return new Promise((resolve) => setTimeout(resolve, 500))
  },

  changeShareImg() {
    this.setData({
      shareTitle: '技师找工作',
      shareImg: 'https://m.xianmaiyangsheng.com/xcxImg/image/refund-share2.png',
      sharePath: '/pages/candidate/candidate'
    })
    setTimeout(() => {
      this.setData({
        shareTitle: '招供货商合作',
        shareImg: '',
        sharePath: '/pages/bidding/bidding'
      })
    }, 1000)
  },
  /**
   * 用户点击右上角分享
   */
  async onShareAppMessage() {
    this.setData({
      sharePath: `${this.data.sharePath}?otherId=${
        wx.getStorageSync('userInfo').user_id
      }&time=${+new Date()}`
    })
    await this.sleep()
    return {
      title: this.data.shareTitle,
      imageUrl: this.data.shareImg,
      path: this.data.sharePath
    }
  }
})
